<?php

namespace App\Http\Controllers\Cruise\Web;

use App\Http\Controllers\BaseController;
use App\Library\Rms\RmsUserApi;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Kms\User\KmsUser;
use App\Service\BaseService;
use App\Service\Cruise\Check\CruiseCheckCompanyService;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;


class CruiseCheckCompanyController extends BaseController
{
    /**
     * 选择供应商
     * @param Request $request
     * @return JsonResponse
     */
    public function frontCompany(Request $request): JsonResponse
    {
        return $this->success(CruiseCheckCompanyService::frontCompany());
    }

    /**
     * 选择用户信息
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function frontUserInfo(Request $request): JsonResponse
    {
        $this->validate($request, [
            'id' => 'required|int'
        ]);

        return $this->success(CruiseCheckCompanyService::frontUserInfo($request->id));
    }

    /**
     * 添加&修改 供应商配置
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function save(Request $request): JsonResponse
    {
        $this->validate($request, [
            'fsCompanyId'      => 'required|int',
            'kfManagerId'      => 'required|int',  //夸父负责人
            'companyManagerId' => 'required|int',  //品控供应商负责人
        ]);
        //信息入库
        $id = $request->post('id', 0);
        CruiseCheckCompanyService::save($id, $request->fsCompanyId, $request->kfManagerId, $request->companyManagerId);

        return $this->success();
    }

    /**
     * 供应商配置列表
     * @param Request $request
     * @return JsonResponse
     *
     */
    public function list(Request $request): JsonResponse
    {
        $pageNum     = (int)$request->get('pageNum', 1);
        $pageSize    = (int)$request->get('pageSize', 10);
        $companyId   = (int)$request->get('companyId', '');
        $kfManagerId = (int)$request->get('kfManagerId', 0);
        return $this->success(CruiseCheckCompanyService::list($pageSize, $pageNum, $companyId, $kfManagerId));
    }

    /**
     * 删除供应商配置
     * @param Request $request
     * @param $id
     * @return JsonResponse
     *
     */
    public function delete(Request $request, $id): JsonResponse
    {
        CruiseCheckCompanyService::delete($id);
        return $this->success();
    }

    /**
     * 供应商状态操作
     * @param Request $request
     * @param $id
     * @return JsonResponse
     * @throws ValidationException
     */
    public function able(Request $request, $id): JsonResponse
    {
        $this->validate($request, [
            'status' => 'required|int'
        ]);

        CruiseCheckCompanyService::able($id, $request->status);

        return $this->success();
    }


    /**
     * 供应商配置详情
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function detail(Request $request, $id): JsonResponse
    {
        return $this->success(CruiseCheckCompanyService::detail($id));
    }


    /**
     * 查询供应商 select
     * @param Request $request
     * @return JsonResponse
     */
    public function selectCompany(Request $request): JsonResponse
    {
        return $this->success(CruiseCheckCompanyService::selectCompany());
    }


    /**
     * 获得员工列表
     * @param Request $request
     * @return JsonResponse
     */
    public function staffList(Request $request): JsonResponse
    {
        $pageNum   = (int)$request->get('pageNum', 1);
        $pageSize  = (int)$request->get('pageSize', 10);
        $companyId = (int)$request->get('companyId', 0);
        $username  = (string)$request->get('username', '');
        $mobile    = (string)$request->get('mobile', '');
        return $this->success(CruiseCheckCompanyService::staffList($pageNum, $pageSize, $companyId, $username, $mobile));
    }


    /**
     * 获得品控服务商列表
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function qualityControlCompanyList(Request $request): JsonResponse
    {
        $this->validate($request, [
            'name' => 'string',
        ]);

        $name = (string)$request->get('name', '');

        if (!strlen($name)) {
            return $this->success(['list' => []]);
        }

        return $this->success(['list' => CruiseCheckCompanyService::qualityControlCompanyList($name)]);
    }


    /**
     * 修改、添加员工信息
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws GuzzleException
     */
    public function saveStaffInfo(Request $request): JsonResponse
    {
        $this->validate($request, [
            'companyIds' => 'required|array',
            'username'   => 'required|string',
            'mobile'     => 'required|string',
        ]);

        $userId     = (int)$request->post('userId', 0);
        $companyIds = (array)$request->post('companyIds');
        $username   = (string)$request->post('username');
        $mobile     = (string)$request->post('mobile');
        $password   = (string)$request->post('password');
        $status     = (int)$request->post('status', 0);

        if (!preg_match("/^1\d{10}$/", $mobile)) {
            return $this->fail(400, '手机号格式校验失败');
        }

        CruiseCheckCompanyService::saveStaffInfo($userId, $companyIds, $username, $mobile, $password, $status);
        return $this->success();
    }


    /**
     * 修改员工状态
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws GuzzleException
     */
    public function updateStaffStatus(Request $request): JsonResponse
    {
        $this->validate($request, [
            'userId' => 'required|int',
            'status' => 'required|int',
        ]);

        $userId     = (int)$request->post('userId', 0);
        $status     = (int)$request->post('status', 0);

        CruiseCheckCompanyService::updateStaffStatus($userId, $status);
        return $this->success();
    }

    public function getAuditor(Request $request)
    {
        $this->validate($request, [
            'departmentId' => 'required|string'
        ]);

        $fsCompany = FsCompanyModel::query()->where('departmentId', $request->departmentId)->first();
        if (!$fsCompany) {
            BaseService::throwErr('不存在的供应商');
        }

        if ($fsCompany->newId != 0) {
            BaseService::throwErr('不支持稽核机构配置');
        }

        $query = FsCompanyRoleMappingModel::query()->where('fsCompanyId', $fsCompany->id)->get();

        // current users
        $userIds = $query->pluck('rmsUserId')->unique()->values();

        // companyUsers
        $companyUsersIds = FsCompanyUserMappingModel
            ::query()
            ->where('fsCompanyId', $fsCompany->id)
            ->groupBy('rmsUserId')
            ->pluck('rmsUserId');

        // rms userInfo
        $users   = collect((new RmsUserApi())->getUserInfoByIds(array_merge($userIds->toArray(), $companyUsersIds->toArray()))['data'] ?? [])->keyBy('id');

        $currentArr = $query->map(function ($item) use ($users) {
            return [
                'userId'   => $item->rmsUserId,
                'userName' => $users[$item->rmsUserId]['username'] ?? '',
                'roleId'   => $item->roleId,
            ];
        })->toArray();

        $companyUsers = $companyUsersIds->map(function ($userId) use ($users) {
            return [
                'userId'   => $userId,
                'userName' => $users[$userId]['username'] ?? '',
            ];
        })->toArray();

        $current = [];

        foreach ($currentArr as $item) {
            $current[$item['roleId']][] = $item;
        }

        $data = [
            'current' => $current,
            'companyUsers' => $companyUsers,
        ];

        return $this->success($data);
    }

    public function setAuditor(Request $request)
    {
        $this->validate($request, [
            'departmentId' => 'required|string',
            'auditors'     => 'required|array',
        ]);

//        $auditors = [
//            1 => [1,2,3,4],
//        ];

        $auditors = $request->get('auditors');


        $fsCompany = FsCompanyModel::query()->where('departmentId', $request->departmentId)->first();
        if (!$fsCompany) {
            BaseService::throwErr('不存在的供应商');
        }

        if ($fsCompany->newId != 0) {
            BaseService::throwErr('不支持稽核机构配置');
        }

        DB::beginTransaction();

        FsCompanyRoleMappingModel::query()->where('fsCompanyId', $fsCompany->id)->delete();

        foreach ($auditors as $roleId => $userIds) {

            if (!in_array($roleId, array_keys(FsCompanyRoleMappingModel::ROLE_TEXT))) {
                BaseService::throwErr('不存在的roleId');
            }

            foreach ($userIds as $userId) {

                FsCompanyRoleMappingModel::query()->create([
                    'fsCompanyId'            => $fsCompany->id,
                    'rmsUserId'              => $userId,
                    'roleId'                 => $roleId,
                    'fsCompanyUserMappingId' => FsCompanyUserMappingModel::getNewData($fsCompany->id, $userId)->id ?? 0,
                ]);
            }
        }

        DB::commit();

        return $this->success();
    }
}
